package hu.ikti.oamadmin.beans.utils;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Vector;

import javax.faces.model.SelectItem;

import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;

import au.com.bytecode.opencsv.CSVReader;

@Name("countryUtil")
@Scope(ScopeType.APPLICATION)
public class CountryUtil {

	List<SelectItem> items = new Vector<SelectItem>();

	public List<SelectItem> getCountryItems() {
		File file = new File("countries.csv");
		FileInputStream fis;
		try {
			fis = new FileInputStream(file);
			long length = file.length();
			byte[] data = new byte[(int) length];
			fis.read(data);
			parseCsv(new ByteArrayInputStream(data), ';');
			return items;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}

	}

	protected void parseCsv(InputStream is, char separator) throws IOException {
		CSVReader reader = new CSVReader(new InputStreamReader(is), separator);
		String[] line;
		while (null != (line = reader.readNext())) {
			SelectItem item = new SelectItem(line[0], line[0]);
			items.add(item);
		}
	}

}
